﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Xml.Linq;
using System.Xml;

namespace ajax
{
    public class chatengine
    {
        
        
        public static void AddMes(string user,string mes)
        {
            XDocument chatstore = XDocument.Load(HttpContext.Current.Server.MapPath("chat.xml"));
            XElement x = new XElement("chat");
            int id = GetLastMesID()+1;
            x.Add(new XElement("ID",id),new XElement("user",user),new XElement("mes",mes),new XElement("time",DateTime.UtcNow.ToString()));
            chatstore.Root.Add(x);
            chatstore.Save(HttpContext.Current.Server.MapPath("chat.xml"));
            
            
        }

        public static List<XElement> GetChats (int since)
        {
            XDocument chatstore = XDocument.Load(HttpContext.Current.Server.MapPath("chat.xml"));
            return chatstore.Descendants("chat").Where(c => Convert.ToInt32(c.Element("ID").Value) > since).ToList();
        }
        public static int GetLastMesID()
        {
           
            XDocument chatstore = XDocument.Load(HttpContext.Current.Server.MapPath("chat.xml"));
            try
            {
                XElement x = chatstore.Descendants("chat").Last();
                return Convert.ToInt32(x.Element("ID").Value);
            }
            catch (Exception)
            {

                return 0;
            }
           
           
        }
    }
}